from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response

import wsgiref.handlers
import cgi
import string
import time
import datetime

# Google Appengine
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.api import urlfetch
from google.appengine.ext.db import djangoforms

# Database Models
from models import UserSettings
from models import SocialEntity

# Main Page and Login/Out *************************************************************************************
def index(request):
  user = users.get_current_user()
  loginurl = users.create_login_url('/')
  logouturl = users.create_logout_url('/')
  mysetting = UserSettings.all().filter('owner = ', users.get_current_user())
  myentities = SocialEntity.all().filter('owner = ', users.get_current_user())
  myemails = ""
  if (mysetting.count() == 0):
	newuser = UserSettings(emailaddresslist = [] , owner=users.get_current_user(), lastsocialactivity = 0.0, datecreated=datetime.date.today())
   	newuser.put()
  else:
    myemails = mysetting[0].emailaddresslist
  return render_to_response('index.html', 
								{'user': user, 
								 'mysettings' : mysetting,
								 'myentities' : myentities,
								 'myemails' : myemails,
								 'loginurl' : loginurl,
								 'logouturl' : logouturl,
								}
							)

# Add A friend ***********************************************************************************************
# TODO: CHANGE THIS TO djangoforms FOR VALIDATIONS
def addfriend(request):
  if request.method == 'POST':
    #prepare input
    is_valid = True

    if (len(request['firstname']) == 0) or (len(request['lastname']) == 0) or (len(request['email']) == 0):
      is_valid = False
  
    if (is_valid):
      newsocialentity = SocialEntity(firstname=cgi.escape(request['firstname']),
                                   lastname=cgi.escape(request['lastname']),
                                   email=cgi.escape(request['email']),
                                   socialinteractionscore=0,
                                   owner=users.get_current_user(),
                                   dateadded=datetime.date.today())
      newsocialentity.put()
      #request.flash['error'] = 'Item could not be saved'
    return HttpResponseRedirect('/')

# Remove A friend ********************************************************************************************
# TODO: CHANGE THIS TO djangoforms FOR VALIDATIONS
def deletefriend(request):
  if request.method == 'POST':
	if request['friend']:
		myfriend = SocialEntity.get_by_id(int(request['friend']))
		if myfriend:
		  SocialEntity.delete(myfriend)
  return HttpResponseRedirect('/')

# Add An Email ***********************************************************************************************
# TODO: CHANGE THIS TO djangoforms FOR VALIDATIONS
def addemail(request):
  message = ''
  #prepare input
  is_valid = True
  if (len(request['useremailaddress']) == 0):
    is_valid = False
  if (is_valid):
    # first, get user settings object from the Datastore 
    myusersettings = UserSettings.gql("WHERE owner = :1", users.get_current_user()) 
    for onlysetting in myusersettings:
      onlysetting.emailaddresslist.append(cgi.escape(request['useremailaddress']))
      onlysetting.put()
      message += cgi.escape(request['useremailaddress']) + ' added!<br/><br/>'
  if (is_valid == False): 
    message += 'You have to specify an email address!<br/><br/>'
    message += ' <strong>Important:</strong> You must begin copying any emails you would like have the social graph and activity imported from to   <a href="mailto:onegraph.import@gmail.com">onegraph.import@gmail.com</a><br/><br/>'
  message += '<a href="/">Go Back.</a>'
  return render_to_response('addemail.html', 
									{'message': message,}
								)

# Check the Social Activity  ********************************************************************************
def activitycheck(request):
  # first, get user settings object from the Datastore 
  myusersettings = UserSettings.gql("WHERE owner = :1", users.get_current_user()) 
    
  # fetch the social graph updates scraped from e-mail
  getgraph = urlfetch.fetch("http://hinchcliffeandcompany.com/sg_sum.txt")
   
  lines = getgraph.content.splitlines() # turn the file into processable lines
  for line in lines:
    halfs = line.rsplit('|')     # split the string into timestamp and social graph data
    timestamp = eval(halfs[0])
    emails = halfs[1].rsplit(',')   # turn the emails into a nice clean list structure
    # now find the  matching user setting
    mysetting = UserSettings.all().filter('emailaddresslist = ', emails[0])
    # if we found something, that means we located the user that belongs to this social activity
    if (mysetting.count() > 0):
      mysetting.get()
      currentowner = mysetting[0].owner
      for myemail in emails:
        if ((myemail != emails[0]) and (mysetting[0].lastsocialactivity < timestamp)):  # don't add ourselves and don't add repeat data
          myentities = SocialEntity.gql("WHERE owner = :1 and email = :2",
                             currentowner, myemail)
          if (myentities.count() == 0):
            # add the new entity
            newsocialentity = SocialEntity(firstname=" ",
                                     lastname=" ",
                                     email=myemail,
                                     socialinteractionscore=1,
                                     owner=currentowner,
                                     dateadded=datetime.date.today())
            newsocialentity.put()
          else:
            myentity = myentities.get() # Have to do a get cause we're not using an iterator
            myentity.socialinteractionscore = myentity.socialinteractionscore +  1  # increment the socialinteractionscore
            myentity.put()
          for setting in mysetting:
            setting.lastsocialactivity = timestamp # make sure we update the timestamp
            setting.put()
  return render_to_response('activitycheck.html')